﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;

namespace LuaNet
{
    class LuaWriterProxy
    {
        static List<LuaWriterProxy> _Proxies = new List<LuaWriterProxy>();
 
        LuaWriterProxy() 
        {
        	
        }

        public static LuaWriterProxy FindProxy(LuaWriter writer)
        {
            if (writer == null) return null;
            lock (_Proxies)
            return _Proxies.FirstOrDefault(p => p.ManagedWriter == writer);
        }

        public static LuaWriterProxy GetProxy(LuaWriter writer)
        {
            var result = FindProxy(writer);
            if (result == null && writer != null)
            {
                result = new LuaWriterProxy()
                {
                    ManagedWriter = writer
                };
                result.UnmanagedWriter = result.InvokeManagedWriter;
                lock (_Proxies)
                    _Proxies.Add(result);
            }
            return result;
        }

        int InvokeManagedWriter(IntPtr state, IntPtr ptr, UInt32 sz, IntPtr ud)
        {
            LuaState ls = LuaState.FindState(state, true);
            if (ManagedWriter != null && ls != null)
            {
                Byte[] buffer = ptr != IntPtr.Zero ? new Byte[sz] : null;
                if (ptr != IntPtr.Zero)
                {
                    Marshal.Copy(ptr, buffer, 0, (int)sz);
                }
                var res = ManagedWriter(ls, buffer, ls.GetUserData(ud));
                buffer = null;
                return res;
            }
            return 0;
        }

        public LuaWriter ManagedWriter { get; private set; }
        public Lua.lua_Writer UnmanagedWriter { get; private set; }
    }
}
